<template>
	<div class="add_edit">
		<use-box :loading="formLoading" element-loading-background="rgba(255, 255, 255, 1)">
			<div class="dflex_wrap">
				<el-form style="width: 50%;" class="pos_r" :model="item" ref="ruleForm" :rules="rules"
					label-width="90px" v-for="(item, i) in form.ad" :key="i">
					<el-card style="height: 670px;" class="margin_10 owoy" shadow="hover">
						<div class="dflex_sb">
							<h3>广告{{ i + 1 }}</h3>
							<el-tooltip :open-delay="350" content="删除" placement="top" :hide-after="1000"
								:enterable="false" effect="light">
								<div v-if="i != 0" class="el-icon-delete crpr margin_l_20 pos_a" @click="deleteForm(i)">
								</div>
							</el-tooltip>
						</div>
						<el-form-item label="广告标题" class="margin_t_20" prop="title" ref="title">
							<el-input v-model="item.title" placeholder="请输入广告标题" clearable></el-input>
						</el-form-item>
						<el-form-item label="广告名称" class="margin_t_20" prop="name" ref="name">
							<el-input v-model="item.name" placeholder="请输入广告名称" clearable></el-input>
						</el-form-item>
						<el-form-item label="广告图片" prop="img" ref="validImg">
							<uni-file-picker ref="img" v-model="item.imageValue" fileMediatype="image"
								returnType="object" :image-styles="imageStyle" @success="imgUpload(i)"
								@delete="imgDelete(i)" />
						</el-form-item>
						<el-form-item label="广告位置" prop="location" ref="location">
							<el-input type="number" v-model.number="item.location" placeholder="请输入广告位置" clearable
								oninput="value = parseInt(value)">
							</el-input>
							<div class="remark_txt">第 {{ item.location }} 位置为广告 顺序从左到右</div>
						</el-form-item>
						<el-form-item label="广告时间" prop="activityTime" ref="activityTime">
							<el-date-picker v-model="item.activityTime" type="datetimerange" align="center"
								range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
								:picker-options="pickerTimeOptions" unlink-panels class="time"></el-date-picker>
						</el-form-item>
						<el-form-item label="类型">
							<el-radio-group v-model="item.type">
								<el-radio label="网页">网页</el-radio>
								<el-radio label="页面">页面</el-radio>
								<el-radio label="内容">内容</el-radio>
							</el-radio-group>
						</el-form-item>
						<el-form-item label="状态">
							<el-switch v-model="item.state" active-color="#ff6a6c" inactive-color="#bbb"
								:active-value="true" :inactive-value="false"></el-switch>
						</el-form-item>
						<el-form-item v-if="item.type == '页面'" label="页面地址">
							<el-select v-model="item.mpPageUrl" placeholder="请选择"
								@change="urlChange(item.mpPageUrl, i)">
								<el-option v-for="page in urlOptions" :key="page._id"
									:label="page.name + ' ' + page.url" :value="page._id"></el-option>
							</el-select>
							<div class="remark_txt">非必填</div>
						</el-form-item>
						<el-form-item v-if="item.type != '内容'" label="跳转地址" prop="url" ref="url">
							<el-input v-model="item.url" placeholder="请输入跳转地址" clearable @clear="clearUrl(i)">
							</el-input>
							<div class="dflex">
								<div v-if="item.type == '页面'" class="remark_txt margin_r_50">自动获取上面选中的值</div>
								<div v-if="item.type == '页面'" class="remark_txt">{{ item.remark }}</div>
							</div>
						</el-form-item>
						<el-form-item v-show="item.type == '内容'" label="内容" prop="content" ref="content">
							<use-editor :ref="'editor' + i" :editorId="i" @created="editorCreated(i)"
								@editorChange="editorChange"></use-editor>
						</el-form-item>
					</el-card>
				</el-form>
			</div>
			<use-affix v-if="!formLoading" position="bottom" :offset="58">
				<div class="dflex margin_l_50">
					<el-button round icon="el-icon-check" :loading="formBtnLoading" class="confirm-btn"
						@click="submitForm('ruleForm')">提交</el-button>
					<el-button round icon="el-icon-plus" class="add-btn" @click="addForm">添加</el-button>
				</div>
			</use-affix>
		</use-box>
	</div>
</template>

<script>
	const __name = 'wmzmall-shopping-parameter';
	const __mpPage = 'wmzmall-app-wxmini-page';
	export default {
		data() {
			const validateLocation = async (rule, value, callback) => {
				if (!value) {
					return callback(new Error('请输入广告位置'));
				}

				if (this.form.ad.filter(x => x.location == value).length > 1) {
					return callback(new Error('输入的广告位置已存在'));
				}

				callback();
			};
			const validateContent = async (rule, value, callback) => {
				this.form.ad.forEach(x => {
					if (x.type == '内容' && !x.content) {
						return callback(new Error('请输入广告内容'));
					}
				});

				callback();
			};
			return {
				formLoading: false,
				dataId: '',
				form: {
					ad: []
				},
				imageStyle: {
					height: '150px',
					width: '150px'
				},
				pickerTimeOptions: {
					disabledDate(time) {
						return time.getTime() < Date.now() - 3600 * 1000 * 24;
					}
				},
				urlOptions: [],
				rules: {
					title: [{
						required: true,
						message: '请输入广告标题',
						trigger: 'change'
					}],
					name: [{
						required: true,
						message: '请输入广告名称',
						trigger: 'change'
					}],
					img: [{
						required: true,
						message: '请选择广告图片',
						trigger: 'change'
					}],
					location: [{
						required: true,
						validator: validateLocation,
						trigger: 'change'
					}],
					activityTime: [{
						type: 'array',
						required: true,
						message: '请选择广告时间',
						trigger: 'change'
					}],
					url: [{
						required: true,
						message: '请输入跳转地址',
						trigger: 'change'
					}],
					content: [{
						required: true,
						validator: validateContent,
						trigger: 'change'
					}]
				},
				formBtnLoading: false
			};
		},
		methods: {
			async loadData(callback) {
				this.formLoading = true;

				this.urlOptions = [];
				await this.$db[__mpPage].tolist({
					loading: false
				}).then(res => {
					if (res.code == 200) {
						res.datas.forEach(data => {
							this.urlOptions.push(data);
						});
					}
				});

				await this.$db[__name].tofirst({
					loading: false
				}).then(res => {
					this.formLoading = false;
					if (res.code == 200) {
						res.datas = res.datas || {};

						this.dataId = res.datas._id || '';
						res.datas.ad = res.datas.ad || [];

						if (!(res.datas && res.datas.ad.length)) {
							this.form.ad.push({
								title: '',
								name: '',
								imageValue: null,
								img: '',
								location: 0,
								activityTime: [],
								start_time: '',
								end_time: '',
								type: '网页',
								state: false,
								mpPageUrl: '',
								remark: '',
								url: '',
								content: ''
							});
							return;
						}

						res.datas.ad.forEach((x, i) => {
							x.imageValue = {};
							x.imageValue.url = x.img;

							x.activityTime = [];
							x.activityTime.push(x.start_time);
							x.activityTime.push(x.end_time);
						});

						this.form.ad = res.datas.ad;

						if (typeof callback === 'function') {
							callback();
						}
					}
				});
			},
			submitForm(formName) {
				let flag = true;
				for (var idx = this.$refs[formName].length - 1; idx >= 0; idx--) {
					let i = idx;
					this.$refs[formName][idx].validate((valid, obj) => {
						if (!valid) {
							let __obj = this.$api.get_form_prop(obj);

							if (this.$refs[__obj][i].$children.length > 1) {
								let classList = [...this.$refs[__obj][i].$children[1].$el.classList];
								if (classList.find(x => x.indexOf('input') != -1)) {
									this.$refs[__obj][i].$el.querySelector('input').focus();
									this.$refs[__obj][i].$el.querySelector('input').click();
									this.$refs[__obj][i].$el.scrollIntoViewIfNeeded(true);
								} else {
									if (this.$refs[__obj][i].$children[1].$el.querySelector('.w-e-text')
										.innerText == '\n') {
										this.$refs[__obj][i].$children[1].$el.querySelector('.w-e-text').focus();
										this.$refs[__obj][i].$children[1].$el.scrollIntoViewIfNeeded(true);
									}
								}
							} else {
								this.$refs.img[i].choose();
							}

							flag = false;
							return;
						}

						if (flag && i == 0) {
							this.formBtnLoading = true;

							this.form.ad.forEach(x => {
								if (x.activityTime && x.activityTime.length) {
									x.start_time = new Date(x.activityTime[0]).getTime();
									x.end_time = new Date(x.activityTime[1]).getTime();
								}
							});

							if (!this.dataId) {
								this.$db[__name].add(this.form).then(res => {
									if (res.code == 200) {
										this.$message({
											message: '操作成功',
											type: 'success'
										});
										this.loadData();
									}
									this.formBtnLoading = false;
								});
							} else {
								this.$db[__name].update(this.dataId, this.form).then(res => {
									if (res.code == 200) {
										this.$message({
											message: '操作成功',
											type: 'success'
										});
										this.loadData();
									}
									this.formBtnLoading = false;
								});
							}
						}
					});
				}
			},
			addForm() {
				this.form.ad.push({
					title: '',
					name: '',
					imageValue: null,
					img: '',
					location: 0,
					activityTime: [],
					start_time: '',
					end_time: '',
					type: '网页',
					state: false,
					mpPageUrl: '',
					remark: '',
					url: '',
					content: ''
				});
			},
			deleteForm(i) {
				this.$confirm(`此操作将清除该广告，需手动提交！`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.form.ad.splice(i, 1);
				});
			},
			imgUpload(i) {
				this.form.ad[i].img = this.form.ad[i].imageValue.url;
				this.$refs.validImg[i].clearValidate();
			},
			imgDelete(i) {
				this.form.ad[i].imageValue = null;
				this.form.ad[i].img = '';
				this.$refs.ruleForm[i].validateField('img');
			},
			urlChange(data, i) {
				let obj = this.urlOptions.find(x => x._id == data);
				this.form.ad[i].url = obj.url;
				this.form.ad[i].remark = obj.remark;
			},
			clearUrl(i) {
				this.form.ad[i].mpPageUrl = '';
			},
			editorChange(res, i) {
				this.form.ad[i].content = res;

				if (res == '') {
					this.$refs.ruleForm[i].validateField('content');
				} else {
					this.$refs.content[i].clearValidate();
				}
			},
			editorCreated(i) {
				if (this.form.ad[i].content) {
					this.$refs['editor' + i][0].setContent(this.form.ad[i].content);
				}
			}
		},
		created() {
			this.loadData(() => {
				this.$nextTick(() => {
					this.$api.scrollToStorage('.use-box', this.$route.path);
				});
			});
		},
		mounted() {
			this.$nextTick(() => {
				this.$api.scrollOnStorage('.use-box', this.$route.path);
			});
		}
	};
</script>

<style>
	.add_edit>>>.el-input,
	.add_edit>>>.el-textarea,
	.add_edit>>>.editor {
		width: 100%;
	}

	.add_edit>>>.el-input__inner.time {
		width: 100%;
	}

	.add_edit .el-select {
		width: 50%;
	}

	.add-btn>>>i {
		font-size: initial;
	}

	.dflex_wrap {
		align-items: initial;
	}

	>>>.el-card {
		overflow: hidden;
		transition: all 0.4s;
	}

	>>>.el-card::-webkit-scrollbar {
		display: none;
	}

	>>>.el-card:hover {
		overflow-y: overlay;
	}

	>>>.el-card:hover .el-icon-delete {
		opacity: 1;
	}

	.el-icon-delete {
		top: 30px;
		right: 30px;
		font-size: 20px;
		opacity: 0;
		transition: all 0.4s;
		z-index: 9999;
	}

	.el-icon-delete:hover {
		color: #ff6a6c;
	}
</style>
